package cn.wolfcode.shop.controller;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;

import cn.wolfcode.shop.service.IUserService;
import cn.wolfcode.shop.vo.JSONResult;

@RestController
@RequestMapping("/api/users")
public class UserController {

	@Reference
	private IUserService userService;

	@GetMapping
	public String get() {
		return "success";
	}

	/**
	 * 用户注册
	 * 路径/api/users
	 * 动作POST
	 * @param username
	 * @param password
	 * @return
	 */
	@PostMapping
	public JSONResult register(String username, String password) {
		userService.register(username, password);
		return new JSONResult();
	}

	/**
	 * 用户登录
	 * 路径/api/users/token
	 * 方法:POST
	 * @param username
	 * @param password
	 * @return
	 */
	@PostMapping("/tokens")
	public JSONResult login(String username, String password) {
		JSONResult jsonResult = new JSONResult();
		String token = userService.login(username, password);
		HashMap<String, Object> tokenMap = new HashMap<>();
		tokenMap.put("token", token);
		jsonResult.setResult(tokenMap);
		return jsonResult;

	}

	/**
	 * 用户退出
	 * 路径/api/users/token
	 * 方法:DELET
	 * @return
	 */
	@DeleteMapping("/tokens")
	public JSONResult logout(HttpServletRequest request) {
		// token需要自定义请求中设置,如果直接连接带token比较不安全
		String token = request.getHeader("head_token");
		userService.logout(token);
		return new JSONResult();
	}
//	@DeleteMapping("/tokens")
//	public JSONResult logout(@RequestHeader("head_token") String token) {
//		// token需要自定义请求中设置,如果直接连接带token比较不安全
//		userService.logout(token);
//		return new JSONResult();
//	}

}
